package com.cloudcross.ssp.web.back.main.account;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.common.utils.TreeObject;
import com.cloudcross.ssp.model.AccountAuthority;
import com.cloudcross.ssp.model.Resources;
import com.cloudcross.ssp.model.Roles;
import com.cloudcross.ssp.service.IAccountAuthorityService;
import com.cloudcross.ssp.service.IResourcesService;
import com.cloudcross.ssp.service.IRolesService;

@Controller
@RequestMapping("/back/main/account")
public class AccountAuthorityController extends SimpleController {

    @Autowired
    protected IAccountAuthorityService accountAuthorityService;
    @Autowired
    protected IResourcesService        resourcesService;
    @Autowired
    protected IRolesService            roleService;

    @RequestMapping
    public String index() {
        return redirect(page("list"));
    }

    @RequestMapping("list")
    public String list(Model model, @RequestParam HashMap<String, Object> paramMap,
                       @RequestParam(defaultValue = "1") int page) {
        if (paramMap != null) {
            Object obj = paramMap.get("searchValue");
            String searchValue = null;
            if (null != obj) {
                searchValue = String.valueOf(obj).trim();
            }
            paramMap.put("searchValue", searchValue);
        }

        int totalRow = accountAuthorityService.countByParams(paramMap);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        paramMap.put("pager", pager);
        List<AccountAuthority> accountAuthoritys = accountAuthorityService.findByParams(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("accountAuthoritys", accountAuthoritys);
        return page("list");
    }

    public List<TreeObject> treeObjects() {
        List<Resources> rs = resourcesService.findAllResources();
        //转换为树对象
        List<TreeObject> treeObjects = new ArrayList<TreeObject>();
        for (Resources res : rs) {
            if (Integer.parseInt(res.getType()) == 0) {
                TreeObject t = new TreeObject();
                try {
                    PropertyUtils.copyProperties(t, res);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
                treeObjects.add(t);
            }
        }
        for (TreeObject menu : treeObjects) {// 转换为树对象
            List<TreeObject> t = new ArrayList<TreeObject>();
            for (Resources res : rs) {// 转换为树对象
                if (res.getParentId().intValue() == menu.getId().intValue()) {
                    TreeObject s = new TreeObject();
                    try {
                        PropertyUtils.copyProperties(s, res);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                    t.add(s);
                }
            }
            for (TreeObject button : t) {
                List<TreeObject> l = new ArrayList<TreeObject>();
                for (Resources res3 : rs) {// 转换为树对象
                    if (res3.getParentId().intValue() == button.getId().intValue()) {
                        TreeObject p = new TreeObject();
                        try {
                            PropertyUtils.copyProperties(p, res3);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        }
                        l.add(p);
                    }
                }
                button.setChildren(l);
            }
            menu.setChildren(t);
        }
        return treeObjects;
    }

    /**
     * 目前只支持账号与角色一对一分配
     * 
     * @param model
     * @return
     */
    @RequestMapping("authority")
    public String authority(Model model, @RequestParam long accountId) {
        //当前账号名，角色名，角色id
        AccountAuthority accountAuthority = accountAuthorityService.findByAccountId(accountId);
        model.addAttribute("accountAuthority", accountAuthority);
        //返回全部的当前账号的权限resource改为另外的方法
        //返回全部的菜单资源
        model.addAttribute("allResources", treeObjects());
        //返回全部的角色
        List<Roles> allRoles = accountAuthorityService.findAllRoles();
        model.addAttribute("allRoles", allRoles);
        return page("authority");
    }

    @RequestMapping("getRoleResource")
    public @ResponseBody List<Long> getRoleResource(@RequestParam Long roleId) {
        List<Long> roleResources = new ArrayList<Long>();
        roleResources = accountAuthorityService.findRolesResources(roleId);
        return roleResources;
    }

    @RequestMapping("getNowResources")
    public @ResponseBody List<Resources> getNowResources(@RequestParam Long accountId) {
        //返回全部的当前账号的权限resource
        List<Resources> nowRes = resourcesService.findAllResourcesByAccountId(accountId);
        //当前账号的权限resource，怎么可以返回全部的权限resource呢？这里改为和权限管理编辑页保持一致了！!
        //List<AccountResources> nowRes= resourcesService.queryResourcesByAccountId(accountId);
        return nowRes;
    }

    @RequestMapping("save")
    public String save(@RequestParam Long accountId, @RequestParam Long roleId,
                       @RequestParam(defaultValue = "0") Long[] powers) {
        if (!"".equals(powers)) {
            List<Long> rolesRes = roleService.findAllResIdByRole(roleId);
            List<Long> intpower = Arrays.asList(powers);
            List<Long> exceptRes = new ArrayList<Long>();
            for (int i = 0; i < rolesRes.size(); i++) {
                if (intpower.contains(rolesRes.get(i))) {
                    continue;
                } else {
                    exceptRes.add(rolesRes.get(i));
                }

            }
            List<Long> addRes = new ArrayList<Long>();
            for (int i = 0; i < intpower.size(); i++) {
                if (rolesRes.contains(intpower.get(i))) {
                    continue;
                } else {
                    addRes.add(intpower.get(i));
                }
            }
            if (roleId != null) {
                List<String> roleidlists = new ArrayList<String>();
                roleidlists.add(roleId.toString());
                roleService.addAccRole(accountId.toString(), roleidlists);
            } else {
                roleService.deleteAccRole(accountId.toString());
            }
            //往数据库里添加数据
            resourcesService.addAccountNotinResourcess(accountId, exceptRes);
            resourcesService.addAccountResourcess(accountId, addRes);
            //addAccountResourcess方法会把之前的权限先删掉再插入新的权限，而addRes里面的值是除去之前权限里面有的之外，新加的
            //这样传过去，会把之前权限里面有的内容删掉，只插入了新加的，也就是说少岔了之前权限和现在权限里面共有的部分，我觉得应该用intpower
        }
        return redirect("list");
    }

}
